<template>
  <div class="home">
    <van-nav-bar title="小米商城" fixed/>
    
    <div class="content" style="padding-top: 46px;">
      <!-- 搜索框 -->
      <van-search
        v-model="searchValue"
        placeholder="请输入搜索关键词"
        shape="round"
        @search="onSearch"
        @input="onSearchInput"
      >
        <template #right-icon>
          <van-icon name="clear" v-if="searchValue" @click="clearSearch"/>
        </template>
      </van-search>
      
      <!-- 轮播图 -->
      <van-swipe class="swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item v-for="banner in banners" :key="banner.id">
          <img :src="banner.image" :alt="banner.title">
        </van-swipe-item>
      </van-swipe>

      <!-- 分类导航 -->
      <div class="category-nav">
        <van-grid :column-num="4" :border="false">
          <van-grid-item 
            v-for="category in categories.slice(0, 8)" 
            :key="category.id"
            :icon="category.icon"
            :text="category.name"
            @click="$router.push('/category')"
          />
        </van-grid>
      </div>

      <!-- 商品列表 -->
      <div class="product-list">
        <!-- 搜索结果提示 -->
        <div class="search-result" v-if="searchValue">
          <span>搜索 "{{searchValue}}" 的结果</span>
          <van-icon name="clear" @click="clearSearch"/>
        </div>
        <van-card
          v-for="item in filteredProducts"
          :key="item.id"
          :price="item.price"
          :title="item.title"
          :thumb="item.image"
          @click="goToDetail(item.id)"
        >
          <template #footer>
            <van-button size="mini" @click.stop="addToCart(item)">加入购物车</van-button>
          </template>
        </van-card>
        <!-- 无搜索结果提示 -->
        <van-empty 
          v-if="searchValue && !filteredProducts.length"
          description="没有找到相关商品"
        />
      </div>
    </div>

    <!-- 底部导航 -->
    <van-tabbar v-model="active">
      <van-tabbar-item icon="home-o">首页</van-tabbar-item>
      <van-tabbar-item icon="apps-o" to="/category">分类</van-tabbar-item>
      <van-tabbar-item icon="cart-o" :badge="cartCount" to="/cart">购物车</van-tabbar-item>
      <van-tabbar-item icon="orders-o" to="/order">订单</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import { getProducts, getBanners, getCategories } from '@/api'
import { mapState } from 'vuex'

export default {
  name: 'Home',
  data() {
    return {
      active: 0,
      searchValue: '',
      products: [],
      banners: [],
      categories: [],
      searchTimer: null
    }
  },
  computed: {
    ...mapState({
      cartList: state => state.cartList
    }),
    cartCount() {
      return this.cartList.length || ''
    },
    filteredProducts() {
      if (!this.searchValue) return this.products
      const keyword = this.searchValue.toLowerCase()
      return this.products.filter(product => 
        product.title.toLowerCase().includes(keyword) ||
        product.description.toLowerCase().includes(keyword)
      )
    }
  },
  created() {
    this.fetchProducts()
    this.fetchBanners()
    this.fetchCategories()
  },
  methods: {
    async fetchProducts() {
      try {
        const res = await getProducts()
        if (res.code === 0) {
          this.products = res.data
        }
      } catch (error) {
        console.error(error)
      }
    },
    async fetchBanners() {
      try {
        const res = await getBanners()
        if (res.code === 0) {
          this.banners = res.data
        }
      } catch (error) {
        console.error(error)
      }
    },
    async fetchCategories() {
      try {
        const res = await getCategories()
        if (res.code === 0) {
          this.categories = res.data
        }
      } catch (error) {
        console.error(error)
      }
    },
    onSearch() {
      // 执行搜索，可以添加额外的搜索逻辑
    },
    onSearchInput() {
      // 防抖处理，避免频繁搜索
      if (this.searchTimer) clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        // 可以在这里添加实时搜索逻辑
      }, 300)
    },
    clearSearch() {
      this.searchValue = ''
    },
    goToDetail(id) {
      this.$router.push({
        path: `/product/${id}`,
        query: { from: 'home' }
      })
    },
    addToCart(product) {
      this.$store.commit('addToCart', product)
      this.$toast('已加入购物车')
    }
  }
}
</script>

<style scoped>
.swipe {
  margin-bottom: 20px;
}
.swipe img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}
.category-nav {
  background: #fff;
  margin-bottom: 10px;
}
.category-nav .van-grid-item__icon {
  font-size: 28px;
}
.category-nav .van-grid-item__text {
  font-size: 12px;
}
.product-list {
  padding: 10px;
}
.search-result {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background: #fff;
  margin-bottom: 10px;
}
.search-result .van-icon {
  color: #999;
}
</style> 